<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '筛选',
  },
}
</route>

<template>
  <view class="bg-#fff"
    :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
  >
    <!-- 走马灯 -->
    <view class="w-750rpx m-a" v-if="filterType === 'talk'">
      <wd-notice-bar 
        text="在了解对方之前，不要透露过多个人信息，包括地址、电话号码等敏感信息。任何要求提供验证码或借钱的行为都可能是骗局，务必保持警惕‌"
        :color="themeConfig.theme === 'dark' ? '#fff': '#1B1116'"
        background-color="rgba(255, 255, 255, 0)"
      >
        <template #prefix>
          <view class="w-32rpx h-32rpx font-size-0 pr-16rpx">
            <wd-img 
              width="100%" 
              height="100%" 
              :src="tips" 
              mode="aspectFill" 
            />
          </view>
        </template>
      </wd-notice-bar>
    </view>
    <!-- searchType eveningTalk -->
    <view class="w-center">
      <wd-text custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="城市" size="32rpx"
      ></wd-text>

      <view class="flex flex-wrap mb-12rpx mt-12rpx" @click="toSelectAddress">
        <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-26rpx mr-24rpx mb-20rpx leading-0 selected color-white">
          {{ city || '全国' }}
        </view>
      </view>

      <wd-text custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="性别" size="32rpx"
      ></wd-text>
      <view class="flex flex-wrap mb-12rpx mt-12rpx">
        <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-26rpx mr-24rpx mb-20rpx leading-0"
          v-for="item in genderList" 
          :key="item.id"
          :class="[{ 'selected color-white': item.typeCode === formState['gender'] }]"
          @click="handleChangeType('gender', item.typeCode)"
        >{{ item.typeName || '--' }}</view>
      </view>
    </view>

    <view class="w-center !mb-6rpx">
      <wd-text 
        custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="年龄" size="32rpx"
      ></wd-text>
    </view>
    
    <view class="w-center m-a font-size-26rpx !mb-32rpx color-#696969" @click="toRangePicker('age')">
      <block v-if="formState.ages">
        <text class="inline-block">从</text>
        <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex mx-8rpx">
          <text class="font-size-24rpx mr-16rpx color-#9C6DEF">{{ formState.ages[0] }}岁</text>
          <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
        </view>
        <text class="inline-block">到</text>
        <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex mx-8rpx">
          <text class="font-size-24rpx mr-16rpx color-#9C6DEF">{{ formState.ages[1] }}岁</text>
          <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
        </view>
      </block>
      <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex" v-else>
        <text class="font-size-24rpx mr-16rpx color-#9C6DEF">不限</text>
        <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
      </view>
    </view>
    
    <view class="w-center !mb-6rpx">
      <wd-text custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="身高" size="32rpx"
      ></wd-text>
    </view>
    
    <view class="w-center m-a font-size-26rpx !mb-32rpx color-#696969" @click="toRangePicker('height')">
      <block v-if="formState.heights">
        <text class="inline-block">从</text>
        <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex mx-8rpx">
          <text class="font-size-24rpx mr-16rpx color-#9C6DEF">{{ formState.heights[0] }}cm</text>
          <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
        </view>
        <text class="inline-block">到</text>
        <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex mx-8rpx">
          <text class="font-size-24rpx mr-16rpx color-#9C6DEF">{{ formState.heights[1] }}cm</text>
          <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
        </view>
      </block>
      <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex" v-else>
        <text class="font-size-24rpx mr-16rpx color-#9C6DEF">不限</text>
        <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
      </view>
    </view>
    
    <view class="w-center !mb-6rpx">
      <wd-text custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="体重" size="32rpx"
      ></wd-text>
    </view>
    
    <view class="w-center m-a font-size-26rpx !mb-32rpx color-#696969" 
      @click="toRangePicker('weight')"
    >
      <block v-if="formState.weights">
        <text class="inline-block">从</text>
        <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex mx-8rpx">
          <text class="font-size-24rpx mr-16rpx color-#9C6DEF">{{ formState.weights[0] }}kg</text>
          <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
        </view>
        <text class="inline-block">到</text>
        <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex mx-8rpx">
          <text class="font-size-24rpx mr-16rpx color-#9C6DEF">{{ formState.weights[1] }}kg</text>
          <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
        </view>
      </block>
      <view class="w-156rpx h-36rpx bg-#FAF7FF rounded-8rpx flex-center !inline-flex" v-else>
        <text class="font-size-24rpx mr-16rpx color-#9C6DEF">不限</text>
        <i class="iconfont icon-arrow-down font-size-20rpx color-#BBB"></i>
      </view>
    </view>

    <view class="w-center">
      <wd-text class="mr-20rpx mb-6rpx block" text="婚姻状况" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        size="32rpx"
      ></wd-text>
      <view class="flex flex-wrap mb-12rpx mt-12rpx">
        <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-28rpx mr-24rpx mb-20rpx leading-0 color-#696969"
          v-for="item in getMatrimonyList" 
          :key="item.id"
          :class="[{ 'selected color-white': item.typeCode === formState.maritalStatus }]"
          @click="handleChangeType('maritalStatus', item.typeCode)"
        >{{ item.typeName || '--' }}</view>
      </view>
    </view>
    
    <view class="w-center">
      <wd-text custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="行业/职业" size="32rpx"
      ></wd-text>
      <view class="flex flex-wrap mb-12rpx mt-12rpx" @click="toProfession">
        <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-26rpx mr-24rpx mb-20rpx leading-0"
          :class="[{ 'selected color-white': professionName }]"
        >
          {{ professionName || '不限' }}
        </view>
      </view>
    </view>

    <!-- <view class="w-center">
      <wd-text custom-style="display: inline-block;margin-right: 10rpx" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        text="城市" size="32rpx"
      ></wd-text>

      <view class="flex flex-wrap mb-12rpx mt-12rpx" @click="toSelectAddress">
        <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-26rpx mr-24rpx mb-20rpx leading-0 selected color-white">
          {{ city || '全国' }}
        </view>
      </view>
    </view> -->
    
    <view class="w-center">
      <wd-text class="mr-20rpx mb-6rpx block" text="年收入" 
        :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
        size="32rpx"
      ></wd-text>
      <view class="flex flex-wrap mb-12rpx mt-12rpx">
        <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-28rpx mr-24rpx mb-20rpx leading-0 color-#696969"
          v-for="item in getIncomeList" 
          :key="item.id"
          :class="[{ 'selected color-white': item.typeCode === formState.incomeStatus }]"
          @click="handleChangeType('incomeStatus', item.typeCode)"
        >{{ item.typeName || '--' }}</view>
      </view>
    </view>
    
    <view class="w-center" v-if="filterType === 'index'">
      <!-- 其它字典中的筛选项 -->
      <block v-for="(filterItem, index) in filterList" :key="index">
        <wd-text class="mr-20rpx mb-6rpx block" :text="filterItem.title" 
          :color="themeConfig.theme === 'dark' ? '#fff' : '#000'" 
          size="32rpx"
        ></wd-text>
        <view class="flex flex-wrap mb-12rpx mt-12rpx">
          <view class="flex-center h-46rpx pl-32rpx pr-32rpx rounded-full font-size-28rpx mr-24rpx mb-20rpx leading-0 color-#696969"
            v-for="item in filterItem.list" 
            :key="item.id"
            :class="[{ 'selected color-white': item.typeCode === formState[filterItem.type] }]"
            @click="handleChangeType(filterItem.type, item.typeCode)"
          >{{ item.typeName || '--' }}</view>
        </view>
      </block>
    </view>

    <!-- 底部占位 -->
    <view class='w-full h-124rpx'
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
    ></view>
    
    <view class="w-750rpx m-a flex-center fixed left-0 bottom-0 bg-#fff box-sd"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
      :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
    >
      <view class="flex-sb-center w-424rpx py-32rpx">
        <view class="btn-full-r16 btn-w-164 btn-h-60">
          <wd-button 
            plain
            @click="back"
          >取消</wd-button>
        </view>
        <view class="btn-full-r16 btn-w-164 btn-h-60">
          <wd-button 
            @click="submit"
          >确定</wd-button>
        </view>
      </view>
    </view>
  </view>
</template>
  
<script lang="ts" setup>
import { enumParams } from '@/enum';
import { Main } from '@/service/types';
import { useCommonStore } from '@/store';
import { useThemeStore } from '@/store';
import { back } from '@/utils';
import { tips } from "@/static/base64";
import { deepClone } from 'wot-design-uni/components/common/util';

// 主题颜色
const { themeConfig } = useThemeStore();
// 获取字典
const useCommon = useCommonStore();
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();

const city = ref('');
const genderList = ref([
  { id: '16825854122', typeCode: '0', typeName: '男' },
  { id: '16825854123', typeCode: '1', typeName: '女' },
  { id: '16825854124', typeCode: 'none', typeName: '不限' },
]);

const submit = () => {
  let str = '';
  const option = {
    ages: '岁',
    heights: 'cm',
    weights: 'kg',
  }
  const dictNameOption = {
    incomeStatus: 'income', // 收入情况
    carHouseStatus: 'assets', // 房车情况
    educationLevel: 'education', // 最高学历/文化层次
    maritalStatus: 'matrimony', // 婚姻状况
  }
  const stateNameList = [
    'gender', 'ages', 'heights', 'weights', 
    'maritalStatus', 'profession', 'incomeStatus', 
    'carHouseStatus', 'educationLevel', 'zodiac', 'cnZodiac'
  ]
  stateNameList.forEach(key => {
    if (formState[key] === 'none') return;
    if (formState[key] && str !== '') {
      str += ',';
    }
    if (key === 'gender') {
      str += formState[key] === '0' ? '男' : '';
      str += formState[key] === '1' ? '女' : '';
      return;
    }
    if (['ages', 'heights', 'weights'].includes(key) && formState[key] && formState[key].length) {
      str += `${formState[key][0]}-${formState[key][1]}${option[key]}`;
      return;
    }
    if (formState[key]) {
      const name = dictNameOption[key] || key;
      const list = useCommon.commonState.dictInfo[name] || [];
      const dictInfoItem = list.find(item => item.typeCode === formState[key]);
      str += dictInfoItem ? dictInfoItem.typeName : '';
    }
  })

  for (const key in formState) {
    if (formState[key] === 'none') {
      formState[key] = '';
    }
  }
  
  uni.$emit(`${filterType.value}UpdateFilter`, JSON.stringify({ formStr: str, filterData: formState }));
  back();
}

/** 筛选条件 */
const filterList = computed(() => {
  let i = 0;
  const list = [];
  // 字典对象
  const dictInfo = deepClone(useCommon.commonState.dictInfo) || {};
  // 字典类型名字与formState中的字段名不一致，所以做一次映射
  for (const key in enumParams.dictNameOptions) {
    // formState的字段名
    const formStateKey = enumParams.dictNameOptions[key] || [];
    // 字典列表，key为字典类型
    const dictInfoList = dictInfo[key] || [];
    // 字典列表第一个元素，用于获取字典类型名称
    const firstItem = dictInfoList[0] || {} as Main.DictInfo;

    const index = dictInfoList.findIndex((item) => {
      return item.typeCode === 'none';
    })
    if (index >= 0) {
      // dictInfoList[index].typeCode = '';
    } else {
      dictInfoList.push({
        id: +new Date() + i, typeCode: 'none', typeName: '不限'
      })
    }

    list.push({
      type: formStateKey,
      title: firstItem.belongToName,
      list: dictInfoList.filter(item => item.typeName !== '保密')
    })
  }
  return list
})

// 获取收入列表
const getIncomeList = computed(() => {
  const incomeList = deepClone(useCommon.commonState.dictInfo['income']) || [];
  incomeList.push({
    id: +new Date(), typeCode: 'none', typeName: '不限'
  })
  return incomeList;
})

// 获取婚姻状况列表
const getMatrimonyList = computed(() => {
  const matrimonyList = deepClone(useCommon.commonState.dictInfo['matrimony']) || [];
  const index = matrimonyList.findIndex((item) => {
    return item.typeCode === 'none';
  })
  if (index >= 0) {
    // matrimonyList[index].typeCode = '';
  } else {
    matrimonyList.push({
      id: +new Date(), typeCode: 'none', typeName: '不限'
    })
  }
  return matrimonyList;
})

// 数据回填
const backfill = (data) => {
  const _intState = JSON.parse(JSON.stringify(data));
  for (const key in data) {
    formState[key] = _intState[key];
  }

  professionName.value = getTypeName();
  city.value = getCityName(formState);
}

// 根据地区id获取地区名称
const getCityName = (data) => {
  const { provinceId, cityId, districtId } = data || {};
  const list = useCommon.commonState.regionInfo || [];
  const provinceItem = list.find(item => item.id == provinceId) || { name: '', children: [] };
  const cityItem = provinceItem.children.find(item => item.id == cityId) || { name: '', children: [] };
  const districtItem = cityItem.children.find(item => item.id == districtId) || { name: '' };

  const cityList = [provinceItem.name, cityItem.name, districtItem.name].filter(item => !!item);
  if (cityList[0] == cityList[1]) {
    cityList.shift();
  }
  return cityList.join('');
}

/** 改变选择的值 */
const handleChangeType = (type, typeCode) => {
  if (formState[type] === typeCode) {
    formState[type] = '';
    return
  }
  formState[type] = typeCode;
}

// 去选择地区页面
const toSelectAddress = () => {
  const { provinceId, cityId, districtId } = formState || {} as any;
  const list = [provinceId, cityId, districtId].filter(item => !!item);

  if (filterType.value === 'index') {
    uni.navigateTo({
      url: '/feature/areaPicker?type=1&page=Filter&areaStr=' + list.join(','),
    })
    return
  }
  uni.navigateTo({
    url: '/feature/areaPicker?page=Filter&areaStr=' + list.join(','),
  })
}

// 去选择年龄/身高/体重页面
const toRangePicker = (type = 'age') => {
  const dataList = formState[`${type}s`] || [];
  const data = dataList.join(',');
  uni.navigateTo({
    url: '/feature/rangePicker?page=Filter&type=' + type + '&data=' + data,
  })
}

const professionName = ref('');
const getTypeName = (name = 'profession') => {
  const list = useCommon.commonState.dictInfo[name] || [];
  const item = list.find(item => item.typeCode === formState[name]) || { typeName: '' };
  return item.typeName || ''
}

// 去选择行业/职业
const toProfession = () => {
  uni.navigateTo({
    url: '/feature/school?page=Filter&type=profession&isNo=1&typeCode=' + formState.profession,
  })
}

// 更新年龄/身高/体重
function handleUpdateData(data) {
  if (!data) return;
  const { type, dataList } = JSON.parse(data);
  if (dataList[0] == '0') {
    formState[`${type}s`] = undefined;
    return
  }
  formState[`${type}s`] = dataList;
}

// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formState, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formState, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}

// 更新学校/行业
function handleUpdateSchool(_data) {
  if (!_data) return;
  const { type, data } = JSON.parse(_data);
  formState[type] = data.typeCode || '';
  professionName.value = data.typeName || '';
}

const initIndexState = {
  ages: undefined, // 年龄范围
  heights: undefined, // 身高范围
  weights: undefined, // 体重范围
  gender: '', // 性别
  incomeStatus: '', // 收入情况
  educationLevel: '', // 最高学历/文化层次
  carHouseStatus: '', // 房车情况
  zodiac: '', // 星座
  cnZodiac: '', // 属相
  generation: '', // 80后、90后等
  maritalStatus: '', // 婚姻状况
  provinceId: '', 
  cityId: '', 
  districtId: ''
}

const initTalkState = {
  ages: undefined, // 年龄范围
  heights: undefined, // 身高范围
  weights: undefined, // 体重范围
  incomeStatus: '', // 收入情况
  gender: '', // 性别
  profession: '', // 行业/职业
  maritalStatus: '', // 婚姻状况
  provinceId: '', 
  cityId: '', 
  districtId: ''
}
const formState = reactive<any>({});

const filterType = ref('index');
onLoad((options) => {
  uni.$on('updateRangeFilter', handleUpdateData);
  uni.$on('updateAreaFilter', handleUpdateArea);
  uni.$on('updateSchoolFilter', handleUpdateSchool);
  
  const { data, type } = options || {};
  filterType.value = type || 'index';

  if (type == 'talk') {
    Object.assign(formState, JSON.parse(JSON.stringify(initTalkState)));
  } else {
    Object.assign(formState, JSON.parse(JSON.stringify(initIndexState)));
  }

  if (!data) return;
  const _data = JSON.parse(data);
  backfill(_data);
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateRangeFilter', handleUpdateData);
  uni.$off('updateAreaFilter', handleUpdateArea);
  uni.$off('updateSchoolFilter', handleUpdateSchool);
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '筛选';
    if (filterType.value !== 'index') {
      themeConfig.title = '筛选通话对象';
      // #ifdef H5
      setTimeout(() => {
        document.title = '筛选通话对象';
      }, 0)
      // #endif
    }
  })
})
</script>

<style lang="scss" scoped>
:deep(.wd-notice-bar) {
  padding-right: 0 !important;
}
.selected {
  background: linear-gradient( 180deg, #9C6DEF 0%, #E5C4FF 100%);
}
</style>